#!/usr/bin/env python
# -*- coding: utf-8 -*-

from django.http import HttpResponse
from django.shortcuts import render_to_response
from django.shortcuts import redirect
from django.db.models import Q
from django.template import RequestContext
from django.core.paginator import Paginator, InvalidPage, EmptyPage
from django.db.models import Count
from django.contrib.auth import logout
from django.conf import settings

from everlog.weblog.forms import PostForm
from everlog.weblog import models

from numbers import Number 
import re

def index(request):
    """home page"""
    posts_all = models.Post.objects.filter(type='post').extra(order_by=['-date'])
    paginator = Paginator(posts_all, settings.PAGE_COUNT)
    try:
        page = int(request.GET.get('page', '1'))
    except ValueError:
        page = 1 
    try:
        posts = paginator.page(page)
    except (EmptyPage, InvalidPage):
        posts = paginator.page(paginator.num_pages)
    return render_to_response('themes/' + settings.THEME + '/index.html',
        {"posts":posts},
        context_instance=RequestContext(request))
    
def tag(request, tag_id):
    """ show all the posts under the tags"""
    posts_tag = models.Post.objects.filter(Q(tags__id__exact=tag_id) | Q(type='post'))
    paginator = Paginator(posts_tag, settings.PAGE_COUNT)
    try:
        page = int(request.GET.get('page','1'))
    except ValueError:
        page = 1
    try:
        posts = paginator.page(paginator.num_pages)
    except (EmptyPage, InvalidPage):
        posts = paginator.page(paginator.num_pages)
    return render_to_response('themes/' + settings.THEME + '/index.html',
        {"posts":posts},
        context_instance=RequestContext(request))

def year(request, year):
    """ all posts of the year """
    try:
        year = int(year)
    except ValueError:
        raise Http404()

    posts_year = models.Post.objects.filter(date__year=year, type='post')
    paginator = Paginator(posts_year, settings.PAGE_COUNT)
    try:
        page = int(request.GET.get('page','1'))
    except ValueError:
        page = 1 
    try:
        posts = paginator.page(paginator.num_pages)
    except (EmptyPage, InvalidPage):
        posts = paginator.page(paginator.num_pages)
    return render_to_response('themes/' + settings+THEME + '/index.html',
        {"posts":posts},
        context_instance=RequestContext(request))

def month(request, year, month):
    """ all posts of the month """
    try:
        month = int(month)
    except ValueError:
        raise Http404()

    posts_month = models.Post.objects.filter(date__year=year, date__month=month, type='post')
    paginator = Paginator(posts_month, settings.PAGE_COUNT)
    try:
        page = int(request.GET.get('page','1'))
    except ValueError:
        page = 1
    try:
        posts = paginator.page(paginator.num_pages)
    except (EmptyPage, InvalidPage):
        posts = paginator.page(paginator.num_pages)
    return render_to_response('themes/' + settings.THEME + '/index.html',
        {"posts":posts},
        context_instance=RequestContext(request))

def search(request):
    """ search post by keyword
        k is the post argument
    """
    if 'k' in request.GET:
        keyword = request.GET['k']
    else:
        keyword = ''

    posts_search = models.Post.objects.filter(content__contains=keyword, type='post')
    paginator = Paginator(posts_search, settings.SEARCH_COUNT)
    try:
        page = int(request.GET.get('page','1'))
    except ValueError:
        page = 1
    try:
        posts = paginator.page(paginator.num_pages)
    except (EmptyPage, InvalidPage):
        posts = paginator.page(paginator.num_pages)
    return render_to_response('themes/' + settings.THEME + '/index.html',
        {"posts":posts, "keyword": keyword},
        context_instance=RequestContext(request))

def post(request, year, month, slug_id):
    """a single post"""
    try:
        year = int(year)
        month = int(month)
    except ValueError:
        raise Http404()

    
    try:
        if slug_id.isdecimal():
            post = models.Post.objects.get(id=slug_id)
        else:
            post = models.Post.objects.get(slug=slug_id)
    except:
        raise Http404()

    if not post:
        raise Http404()

    #comment
    if request.method == 'POST':
        form = PostForm(request.POST)
        if form.is_valid():
            cd = form.cleaned_data
            comment = models.Comment(post = post,
                    author = cd['name'],
                    author_email = cd['email'],
                    author_url = cd['website'],
                    author_ip = request.META['REMOTE_ADDR'],
                    content = cd['content'],
            )
            comment.save()
    else:
        form = PostForm()
    comments = models.Comment.objects.filter(post=post)

    #check previous exists
    previous = models.Post.objects.filter(id__gt=post.id)
    if len(previous)>0:
        post_previous = previous[0]
    #check next exists
    next = models.Post.objects.filter(id__lt=post.id)
    if len(next)>0:
        post_next = next[0]
    return render_to_response('themes/' + settings.THEME + '/post.html',
        locals(),
        context_instance=RequestContext(request))

def logout_view(request):
    logout(request)
    return redirect(index)

def import_view(request):
    """import data from xml"""
    return render_to_response('themes/' + settings.THEME + '/import.html',
        locals(),
        context_instance=RequestContext(request))
